<?php

namespace App\Kuafu\Base\Command\Traits;

use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Validator;

trait KfGetTimeInterval
{
    /**
     * 时间范围确认
     *
     * @return array|void
     */
    public function getTimeInterval()
    {
        $isDirect = $this->input->getOption('d');
        switch ($isDirect) {
            case 'false':
                $startTimeAt = $this->ask('请输入开始日期 : 例. 2012-10-01');
                $endTimeAt   = $this->ask('请输入截止日期 : 例. 2012-11-01');

                if (!empty($startTimeAt) || !empty($endTimeAt)) {
                    Validator::extend('compareDateTime',
                        function ($attribute, $value, $parameters, \Illuminate\Validation\Validator $validator) {
                            $validator->requireParameterCount(1, $parameters, 'compareDateTime');
                            $comparedToValue = $validator->getData()[$parameters[0]];
                            return strtotime($value) > strtotime($comparedToValue);
                        });

                    $validateResult = Validator::make(['startTime' => $startTimeAt, 'endTime' => $endTimeAt], [
                        'startTime' => 'required|string|date_format:Y-m-d',
                        'endTime'   => 'required|string|date_format:Y-m-d|compareDateTime:startTime',
                    ]);

                    if ($validateResult->fails()) {
                        $this->output->error('输入时间格式有误');
                        exit(Command::FAILURE);
                    }
                } else {
                    $startTimeAt = date("Y-m-d 00:00:00", strtotime("-1 day"));
                    $endTimeAt   = date("Y-m-d 00:00:00", time());
                }

                if ($this->confirm(vsprintf('是否执行时间段 [ %s ] - [ %s ] 内的数据？', [$startTimeAt, $endTimeAt]))) {
                    return [strtotime($startTimeAt), strtotime($endTimeAt)];
                }

                $this->info('执行中断');
                exit(Command::FAILURE);
                break;
            case 'true':
                $startTimeAt = date("Y-m-d 00:00:00", strtotime("-1 day"));
                $endTimeAt   = date("Y-m-d 00:00:00", time());
                return [strtotime($startTimeAt), strtotime($endTimeAt)];
                break;
            default:
                $this->output->error('输入参数有误');
                exit(Command::FAILURE);
                break;
        }
    }

}
